#!/usr/bin/env bash
#$ -N fmriprep
#$ -o { project_root }/logs
#$ -q { queue }
#$ -j y
#$ -t 1:{ num_jobs }
#$ -tc { max_jobs }

export PROJECT_ROOT={ project_root }
read SUBJECT <<< $(awk -v id=$SGE_TASK_ID 'NR==id {{print $1}}' { file_sublist })
export SUBJECT

# clean data from previous runs, because freesurfer might error otherwise
prev_dir_pattern=( "sourcedata/freesurfer" "" )
for dir_pattern in "${{prev_dir_pattern[@]}}"
do
    dir=`realpath { path_derivatives }/fmriprep/$dir_pattern/sub-${{SUBJECT}}`
    if [ -d $dir ]; then
        echo [`date "+%Y-%m-%d %H:%M:%S"`] "Remove fmriprep files in ${{dir}} from previous run for subject: ${{SUBJECT}}."
        rm -rf $dir
    fi
done

# do fmriprep
echo [`date "+%Y-%m-%d %H:%M:%S"`] "Begin fmriprep for subject: ${{SUBJECT}}."
{ path_template }/exec_fmriprep.sh
echo [`date "+%Y-%m-%d %H:%M:%S"`] "End fmriprep for subject: ${{SUBJECT}}."

# clean working files
echo [`date "+%Y-%m-%d %H:%M:%S"`] "Clean temporary files generated by fmriprep."
wf_dir={ path_tmp }/fmriprep/fmriprep_23_0_wf/single_subject_${{SUBJECT}}_wf
if [ -d ${{wf_dir}} ]; then
    rm -rf ${{wf_dir}}
fi
echo [`date "+%Y-%m-%d %H:%M:%S"`] "Clean temporary files generated by fmriprep done."
